﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// This class will generate a SHA512 hash from a string with a self supplied salt.
/// </summary>
public static class SHA
{
	public static string generateHash(string input, string saltString)
    {

        // get salt, convert password to bytes, locate array for password+salt
        byte[] salt = Encoding.UTF8.GetBytes(saltString);
        byte[] plainText = Encoding.UTF8.GetBytes(input);
        byte[] plainTextWithSalt = new byte[plainText.Length + salt.Length];

        // add password and salt to byte array
        for (int i = 0; i < plainText.Length; i++) { plainTextWithSalt[i] = plainText[i]; }
        for (int i = 0; i < salt.Length; i++) { plainTextWithSalt[plainText.Length + i] = salt[i]; }

        // define hash algorithm and compute hash
        HashAlgorithm hashAlg = new SHA512Managed();

        // copy hash in byte array, create empty array for hash with salt
        byte[] hash = hashAlg.ComputeHash(plainTextWithSalt);
        byte[] hashWithSalt = new byte[hash.Length + salt.Length];

        // add hash + salt to byte array
        for (int i = 0; i < hash.Length; i++) { hashWithSalt[i] = hash[i]; }
        for (int i = 0; i < salt.Length; i++) { hashWithSalt[hash.Length + i] = salt[i]; }

        // remove endline/carriage return characters from Base64 string.
        string s = Convert.ToBase64String(hashWithSalt);
        byte[] s2 = new byte[s.Length];
        s2 = System.Text.Encoding.UTF8.GetBytes(s);

        return Convert.ToBase64String(s2);
        
    }
}
